<template>
  <div class="recipe-detail">
    <!-- 顶部导航 -->
    <van-nav-bar
      :title="title"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <!-- 菜谱封面图 -->
    <div class="recipe-cover">
      <van-image
        width="100%"
        height="300px"
        fit="cover"
        :src="phone"
      />
    </div>
    
    <!-- 基本信息 -->
    <div class="recipe-meta">
      <div class="meta-item">
        <span>难度:<van-rate v-model="value" readonly allow-half/></span>
      </div>
      <div class="meta-item">
        <span>烹饪时间: {{time}}分钟</span>
      </div>
    </div>
    
    <!-- 用料 -->
    <div class="section">
      <h3 class="section-title">
        <van-icon name="shopping-cart-o" />
        <span>用料</span>
      </h3>
      <div class="ingredients">
        <div class="ingredient-item" v-for="(item, index) in ingredients" :key="index">
          <span class="ingredient-name">{{ item.name }}</span>
          <span class="ingredient-amount">{{ item.amount }}</span>
        </div>
      </div>
    </div>
    
    <!-- 步骤 -->
    <div class="section">
      <h3 class="section-title">
        <van-icon name="orders-o" />
        <span>步骤</span>
      </h3>
      <div class="steps">
        <div class="step-item" v-for="(step, index) in steps" :key="index">
          <div class="step-index">步骤{{ index + 1 }}</div>
          <div class="step-content">{{ step }}</div>
        </div>
      </div>
    </div>
    
    <!-- 底部操作栏 -->
    <div class="action-bar">
      <van-button round type="primary" icon="good-job-o">点赞</van-button>
      <van-button round type="primary" :icon=icons  @click="Collection">收藏</van-button>
    </div>
  </div>
</template>

<script setup name="Recipe_datail">
import { onMounted, ref} from 'vue'
import { getRecipesById,insertFavoriteAll,deleteFavoriteById,selectRecipeId } from '../api/index'
import { useRoute } from 'vue-router';
import { showToast } from 'vant';
import { useUserInfoStore } from '../stores/userInfo'

const route=useRoute()

const userInfoStore=useUserInfoStore()

const RecipeId=ref(route.query.recipeId)

const score = ref(5)

const time=ref()

// 难度评分
const value = ref();

const ret=ref([])
// console.log("name",ret.value.recipes);

const phone=ref()

const title=ref()

const ingredients = ref([]);


const icons=ref('star-o')

const steps = ref([
])
//通过recipeId来展示详细页面
const recipes=async()=>{
  ret.value=await getRecipesById(RecipeId.value)
  // console.log("@@@@",ret.value);
  phone.value=ret.value.recipes.recipesUrl
  value.value=ret.value.recipes.recipesRank
  time.value=ret.value.recipes.updateTime
  ingredients.value=ret.value.recipes.foodMaterials

  const items = ingredients.value.split(';');
// 2. 遍历并提取 name 和 amount
const parsedIngredients = items.map(item => {
  const [name, amount] = item.split(',');
  return { name, amount };
});
ingredients.value=parsedIngredients

const rawSteps=ret.value.recipes.description

steps.value = rawSteps.split(';').map(step => step.trim());
// console.log("@@@@",steps);

title.value=ret.value.recipes.recipesName
// console.log("@@@",title.value);
}

//保存收藏参数
const favorites=ref({
  'userId':0,
  'recipeId':0
})

const favorite=()=>{
  favorites.value.userId=userInfoStore.userId
  favorites.value.recipeId=RecipeId.value
}

//收藏点击事件
const Collection = async () => {
  if(icons.value=="star-o"){
    await collection()
    icons.value="star"
  }else{
    await delectCollection()
    icons.value="star-o"
  }
 
}

// 收藏方法
const collection = async () => {
  // console.log("favorite", favorites)
  
  try {
    const response = await insertFavoriteAll(favorites.value)
    // console.log("收藏成功", response)
    // 添加成功提示
    showToast("收藏成功！")
    // 或者：message.success("收藏成功！")
  } catch (error) {
    console.error("API请求失败:", error)
    throw error // 将错误继续抛出，让外层处理
  }
}

//收藏删除方法
const delectCollection=async()=>{
  try {
    const response = await deleteFavoriteById(RecipeId.value)
    // console.log("删除成功", response)
    // 添加成功提示
    showToast("删除成功！")
    // 或者：message.success("收藏成功！")
  } catch (error) {
    console.error("API请求失败:", error)
    throw error // 将错误继续抛出，让外层处理
  }
}

//判断是否收藏
const isCollection=async()=>{
   let recipeId=await selectRecipeId(favorites.value.userId);
   const isrec=recipeId.includes(Number(RecipeId.value))
  //  console.log("isrec",isrec);
   if(isrec==true){
     icons.value=('star')
   }else{
    icons.value=('star-o')
   }
}

onMounted(()=>{
  favorite()
  recipes()
  isCollection()
})

   

</script>

<style scoped>
.recipe-detail {
  padding-bottom: 60px;
  background-color: #f8f8f8;
}

.recipe-cover {
  position: relative;
}

.recipe-score {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background: rgba(0, 0, 0, 0.5);
  padding: 5px 10px;
  border-radius: 15px;
  color: white;
  display: flex;
  align-items: center;
}

.score-text {
  margin-left: 5px;
  font-size: 12px;
}

.recipe-meta {
  display: flex;
  justify-content: space-around;
  padding: 15px 0;
  background: white;
  margin-bottom: 10px;
}

.meta-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 12px;
  color: #666;
}

.meta-item .van-icon {
  font-size: 16px;
  margin-bottom: 5px;
  color: #ff6b6b;
}

.section {
  background: white;
  margin-bottom: 10px;
  padding: 15px;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  margin-bottom: 15px;
  color: #333;
}

.section-title .van-icon {
  margin-right: 5px;
  color: #ff6b6b;
}

.ingredients {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.ingredient-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px dashed #eee;
}

.ingredient-name {
  color: #333;
}

.ingredient-amount {
  color: #ff6b6b;
}

.steps {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.step-item {
  display: flex;
  gap: 10px;
}

.step-index {
  flex-shrink: 0;
  width: 50px;
  height: 50px;
  background: #ff6b6b;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

.step-content {
  flex-grow: 1;
  padding: 10px;
  background: #f5f5f5;
  border-radius: 8px;
}

.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  padding: 10px;
  background: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.action-bar .van-button {
  width: 45%;
}
</style>
